﻿using HandmadeShop.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HandmadeShop.BusinessLogic.Repositories
{
    public class UnitOfWork : IDisposable
    {
        private HandmadeShopEntities _context;
        private GenericRepository<Account> _accountRepository;
        private GenericRepository<Product> _productRepository;
        private GenericRepository<ProductType> _productTypeRepository;
        private GenericRepository<ProductPrice> _productPriceRepository;

        public UnitOfWork()
        {
            this.Init();
        }

        public UnitOfWork(HandmadeShopEntities context)
        {
            if (context == null)
                this.Init();
            else
                this._context = context;
        }

        private void Init()
        {
            this._context = new HandmadeShopEntities();
        }

        public GenericRepository<Account> AccountRepository
        {
            get
            {
                if (this._accountRepository == null)
                {
                    this._accountRepository = new GenericRepository<Account>(this._context);
                }

                return this._accountRepository;
            }
        }

        public GenericRepository<Product> ProductRepository
        {
            get
            {
                if (this._productRepository == null)
                {
                    this._productRepository = new GenericRepository<Product>(this._context);
                }
                return _productRepository;
            }
        }

        public GenericRepository<ProductType> ProductTypeRepository
        {
            get
            {
                if (this._productTypeRepository == null)
                {
                    this._productTypeRepository = new GenericRepository<ProductType>(this._context);
                }
                return _productTypeRepository;
            }
        }

        public GenericRepository<ProductPrice> ProductPriceRepository
        {
            get
            {
                if (this._productPriceRepository == null)
                {
                    this._productPriceRepository = new GenericRepository<ProductPrice>(this._context);
                }
                return _productPriceRepository;
            }
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this._context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
